package com.esdk.sql.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.esdk.esdk;
import com.esdk.sql.SQLRuntimeException;
import com.esdk.utils.EasyProp;
import lombok.NonNull;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionPoolBuilder{
  public static IConnectionPool createPool(@NonNull final File configfile) throws IOException, PropertyVetoException, SQLException{
    return createPool(DataSourceBuilder.getProperty(configfile));
  }

	public static IConnectionPool createPool(@NonNull InputStream propInputStream){
		try{
			return createPool(esdk.file.getProperties(propInputStream));
		}catch(Exception e){
			throw new SQLRuntimeException(e);
		}
	}

	public static IConnectionPool createPool(@NonNull String propertiesFileName){
		Properties prop=new Properties();
		try{
			prop.load(esdk.file.getInputStream(propertiesFileName));
			return createPool(prop);
		}catch(Exception e){
			throw new SQLRuntimeException(e);
		}
	}


	public static IConnectionPool createPool(@NonNull Properties prop){
		return createPool(new EasyProp(prop),null);
	}

	public static IConnectionPool createPool(@NonNull EasyProp easyProp) {
		return createPool(easyProp,null);
	}

	public static IConnectionPool createPool(@NonNull DataSource dataSource) {
		return createPool(null,dataSource);
	}

	public static IConnectionPool createPool(@NonNull DataSource dataSource,int maxActive) {
		return new EasyConnectionPool(dataSource,maxActive);
	}

	private static IConnectionPool createPool(EasyProp easyProp,DataSource dataSource) {
		return createPool(easyProp,dataSource,null);
  }

	private static IConnectionPool createPool(EasyProp easyProp,DataSource dataSource,Integer maxActive) {
		DataSource ds=esdk.obj.or(dataSource,()->DataSourceBuilder.createDataSource(easyProp));
		return new EasyConnectionPool(ds,esdk.obj.or(maxActive,((DruidDataSource)ds).getMaxActive()));
	}
}
